import json
import os

from json import JSONDecodeError

# 缓存文件目录
CACHE_PATH = os.path.dirname(__file__) + '/../.caches/'
# 缓存文件后缀
CACHE_FILE_EXT = '.cache'


def _path2cache_filename(path: str, version: str = '') -> str:
    """
    缓存文件命名，将项目路径以下划线连接，拼接上版本号命名
    :param path: 项目路径
    :param version: 版本号
    :return: name of cache file
    """
    return path.replace('\\', '_').replace('/', '_').replace(':', '') + (version or '')


def clean(local_basepath: str, version: str = '', clear_all: bool = False):
    """
    删除项目上传缓存记录
    :param local_basepath: 项目路径
    :param version: 版本号
    :param clear_all: 是否删除指定项目所有版本的上传缓存
    """
    if not version:
        if not clear_all:
            print('要删除该项目的所有版本上传缓存，加上-a或--all参数，要不就使用-v或--version指定删除的版本号')
            exit(0)
        else:
            files = os.listdir(CACHE_PATH)
            if files:
                cache_file_prefix = _path2cache_filename(local_basepath)
                for file in files:
                    if file.endswith(CACHE_FILE_EXT) and file.startswith(cache_file_prefix):
                        os.remove(CACHE_PATH + file)
    else:
        cache_file = CACHE_PATH + _path2cache_filename(local_basepath, version) + CACHE_FILE_EXT
        print(cache_file)
        if os.path.exists(cache_file):
            os.remove(cache_file)


def clean_all():
    """
    清除所有项目上传缓存
    """
    files = os.listdir(CACHE_PATH)
    if files:
        for file in files:
            file.endswith(CACHE_FILE_EXT) and os.remove(CACHE_PATH + file)


def save(local_basepath: str, cache_data: dict, version: str = ''):
    """
    保存缓存数据
    :param local_basepath: 项目路径
    :param cache_data: 缓存数据
    :param version: 版本号
    """
    cache_filename = _path2cache_filename(local_basepath, version)
    file = open(CACHE_PATH + cache_filename + CACHE_FILE_EXT, 'w')
    file.write(json.dumps(cache_data))
    file.close()


def get(local_basepath: str, version: str = '') -> dict:
    """
    获取项目上传缓存记录
    :param local_basepath: 项目路径
    :param version: 版本号
    :return: dict
    """
    cache_filename = _path2cache_filename(local_basepath, version)
    cache_file = CACHE_PATH + cache_filename + CACHE_FILE_EXT
    if not os.path.exists(cache_file):
        return dict()
    file = open(cache_file)
    content = file.read()
    try:
        return json.loads(content)
    except JSONDecodeError:
        return dict()
    finally:
        file.close()
